<?php

/**
 * @Author: king
 * @Date:   2019-05-04 17:09:48
 * @Last Modified by:   king
 * @Last Modified time: 2019-06-06 23:24:26
 */
namespace App\Models\Api;
use App\Exceptions\ApiException;
use App\Models\Api\Base;
use AstroTool\Cache\CacheManage;
use Cache;

class LanmeiCounselorProblemPrice extends Base
{
    protected $table = 'counselor_problem_price';

    /**
     * 在数据库中 获取公开悬赏价格
     * @param $type
     * @return array
     * @throws ApiException
     */
    public function getOpenedPriceInData($type)
    {
        try
        {
            $data = $this->where('type', $type)->where(['status' => 1])->orderBy('sort', 'asc')
                ->get(['id','people','price'])->keyBy('id')->toArray();
            // 数据格式为 json
            $priceDataArray = json_encode($data);
        }
        catch (Exception $e)
        {
            throw new ApiException('服务异常', 200, config('code.error'));
        }

        return $priceDataArray;
    }

    /**
     * 获取公开悬赏价格
     * @param $type
     * @return array
     * @throws \Exception
     */
    public function getOpenedPrice($type)
    {
        $data = CacheManage::getInstance()->setCacheConfig('counselor_opened_price',$type)
            ->getDataAndSet(function () use ($type)
            {
                return $this->getOpenedPriceInData($type);
            });

        $priceDataArray = json_decode($data, true);

        return $priceDataArray;
    }

    /**
     * 获取咨询价格
     * @param $id
     * @param $problemType
     * @return array|mixed
     * @throws \Exception
     */
    public function getProblemOpenedPrice($id, $problemType)
    {
        $openedPrices = $this->getOpenedPrice($problemType);

        return $openedPrices[$id] ?? [];
    }
}
